package com.pkk.penguin.util.image.support.utils;

import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @description: 绘制换行的字符串工具类
 * @author: peikunkun
 * @create: 2019-11-11 13:25
 **/
public class Graphics2DDrawUtil {

  /**
   * @param g
   * @param text 文本
   * @param lineHeight 行高
   * @param maxWidth 行宽
   * @param maxLine 最大行数
   * @param left 左边距
   * @param top 上边距
   * @param trim 是否修剪文本（1、去除首尾空格，2、将多个换行符替换为一个）
   * @param lineIndent 是否首行缩进
   */
  public static void drawString(Graphics2D g, String text, float lineHeight, float maxWidth, int maxLine, float left,
      float top, boolean trim, boolean lineIndent) {
    if (text == null || text.length() == 0) {
      return;
    }
    if (trim) {
      text = text.replaceAll("\\n+", "\n").trim();
    }
    if (lineIndent) {
      text = "　　" + text.replaceAll("\\n", "\n　　");
    }
    drawString(g, text, lineHeight, maxWidth, maxLine, left, top);
  }

  /**
   * @param g
   * @param text 文本
   * @param lineHeight 行高
   * @param maxWidth 行宽
   * @param maxLine 最大行数
   * @param left 左边距
   * @param top 上边距
   */
  public static void drawString(Graphics2D g, String text, float lineHeight, float maxWidth, int maxLine, float left,
      float top) {
    if (text == null || text.length() == 0) {
      return;
    }

    FontMetrics fm = g.getFontMetrics();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < text.length(); i++) {
      char c = text.charAt(i);
      sb.append(c);
      int stringWidth = fm.stringWidth(sb.toString());
      if (c == '\n' || stringWidth > maxWidth) {
        if (c == '\n') {
          i += 1;
        }
        if (maxLine > 1) {
          g.drawString(text.substring(0, i), left, top);
          drawString(g, text.substring(i), lineHeight, maxWidth, maxLine - 1, left, top + lineHeight);
        } else {
          g.drawString(text.substring(0, i - 1) + "…", left, top);
        }
        return;
      }
    }
    g.drawString(text, left, top);
  }

  public static String readText(InputStream in, String charset) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, charset));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while (null != (line = reader.readLine())) {
      sb.append(line + "\n");
    }
    return sb.toString();
  }
}
